const fs = require('fs')
const ora = require('ora')
const chalk = require('chalk')
const symbols = require('log-symbols')
const inquirer = require('inquirer')
const shell = require('shelljs')
const path = require('path')

function createTemplate (file, spinner) {
  spinner.text = '创建文件中请稍后...'
  const rs = fs.createReadStream(path.join(__dirname, 'template.vue'));
  const ws = fs.createWriteStream(path.resolve(process.cwd(), './' + file));
  rs.pipe(ws)
  rs.on('end', function () {
    spinner.text = '组件创建成功'
    spinner.succeed()
  })
}

function checkFile (file) {
  const spinner = ora('文件检测中请稍后...')
  spinner.start()
  if (fs.existsSync(path.resolve(process.cwd(), './' + file))) {
    spinner.text = ''
    spinner.fail()
    inquirer.prompt([
      {
        type: 'list',
        message: '文件已存在，是否删除当前的文件,请慎重考虑,删除的文件无法恢复?',
        name: 'type',
        choices: [
          "YES",
          "NO",
        ],
      }
    ]).then(res => {
      if (res.type === 'YES') {
        spinner.text = file + '文件正在删除中请稍后'
        shell.rm('-rf', path.resolve(process.cwd(), `./${file}`));
        spinner.text = file + '文件删除成功';
        createTemplate(file, spinner)
      } else {
        console.log(symbols.error, chalk.red('文件已存在,请更改'))
      }
    })
  } else {
    if (file.endsWith('.vue')) {
      const arr = file.split('/');
      let tempPath = '';
      for (let index = 0; index < arr.length - 1; index++) {
        tempPath += arr[index] + '/'
        if (!(fs.existsSync(path.resolve(process.cwd(), './' + tempPath)))) {
          fs.mkdirSync(tempPath)
        }
      }
      createTemplate(file, spinner);
    } else {
      spinner.text = '文件不符合规范必须是 .vue 结尾'
      spinner.fail()
    }

  }
}

module.exports = {
  init (name) {
    checkFile(name);
  },
}